#!/bin/sh

BOOT_PATH=$(cd `dirname $0`; pwd)
BIN_PATH=${BOOT_PATH}/bin
LOG_PATH=${BOOT_PATH}/logs

start(){
    echo ">>>Server starting..."
    rm -f ${LOG_PATH}/*.out
    rm -f ${LOG_PATH}/*.log
    ${BIN_PATH}/startup.sh
    echo ">>>Server started."
}
stop(){
 	echo ">>>Server stopping..."
    ${BIN_PATH}/shutdown.sh
    sleep 2
    stopall
    echo ">>>Server stopped."
}
stopall(){   
    ps -ef|grep ${BIN_PATH}|grep -v "grep"|awk '{print $2}'|while read pid
	do
		kill $pid
	done
	sleep 2
	ps -ef|grep ${BIN_PATH}|grep -v "grep"|awk '{print $2}'|while read pid
	do
		kill -9 $pid
	done
} 

case "$1" in  
  start)  
    start  
    ;;  
  stop)   
    stop
    ;; 
  stopall)  
    echo ">>>Server stopping..."
    stopall
    echo ">>>Server stopped."
    ;;  
  restart)  
    stop  
    sleep 1
    start  
    ;;  
  stat)
    echo "======================"
    echo "Process Info:"
    ps -ef|grep ${BIN_PATH}|grep -v grep
     
    echo ""
    ps -ef|grep ${BIN_PATH}|grep -v grep|awk '{print $2}'|while read pid
	do
	    echo "--------------"
	    echo "Handler QTY:"
		#lsof -n| sort|uniq -c|sort -nr|grep $pid
		lsof -n|awk '{print $2}'|sort|uniq -c|sort -nr|grep $pid
		
		echo ""
		echo "Socket QTY:"
		ls /proc/$pid/fd -l|grep socket:|wc -l
		echo "---------------"
	done
  	;; 
  port)
    netstat -tunlp |grep $2
  ;;
  log)
  	echo "================================="
  	tail ${LOG_PATH}/catalina.out -n 500
  	echo "================================="
  	;;
  *)  
    echo "Usage: {start|stop|restart|stat|log|port}"  
    ;;  
esac

exit 0
